package com.tang.framework.core;



import com.tang.framework.annotation.DataAuthority;
import com.tang.framework.core.model.LocalContext;
import com.tang.framework.core.model.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;

import java.util.Objects;

/**
 * @Author tang jun liang
 * @Date 2023/8/9 16:07
 */
@Data
public class ContextHold {
    static ThreadLocal<LocalContext> threadLocal = new ThreadLocal<>();


    public static void setLoginUser(LoginUser loginUser) {
        LocalContext localContext = threadLocal.get();
        if (Objects.isNull(localContext)){
            localContext = new LocalContext();
        }
        localContext.setLoginUser(loginUser);
        threadLocal.set(localContext);
    }

    public static void setRequest(HttpServletRequest request) {
        LocalContext localContext = threadLocal.get();
        if (Objects.isNull(localContext)){
            localContext = new LocalContext();
        }
        localContext.setHttpServletRequest(request);
        threadLocal.set(localContext);
    }


    public static void setDataAuthority(DataAuthority dataAuthority) {
        LocalContext localContext = threadLocal.get();
        if (Objects.isNull(localContext)){
            localContext = new LocalContext();
        }
        localContext.setDataAuthority(dataAuthority);
        threadLocal.set(localContext);
    }

    public static LoginUser getLoginUser() {
        LocalContext localContext = threadLocal.get();
        if (Objects.isNull(localContext)){
            return null;
        }
        return localContext.getLoginUser();
    }

    public static DataAuthority getDataAuthority() {
        LocalContext localContext = threadLocal.get();
        if (Objects.isNull(localContext)){
            return null;
        }
        return localContext.getDataAuthority();
    }


    public static HttpServletRequest getRequest() {
        LocalContext localContext = threadLocal.get();
        if (Objects.isNull(localContext)){
            return null;
        }
        return localContext.getHttpServletRequest();
    }


}
